package cn.stylefeng.guns.modular.vote.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.system.SystemUtil;
import cn.stylefeng.guns.modular.history.entity.VoteHistory;
import cn.stylefeng.guns.modular.history.pojo.request.VoteHistoryRequest;
import cn.stylefeng.guns.modular.history.service.VoteHistoryService;
import cn.stylefeng.guns.modular.vote.entity.Works;
import cn.stylefeng.guns.modular.vote.pojo.request.WorksRequest;
import cn.stylefeng.guns.modular.vote.service.WorksService;
import cn.stylefeng.roses.kernel.config.api.context.ConfigContext;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import cn.stylefeng.roses.kernel.system.modular.organization.entity.HrOrganization;
import cn.stylefeng.roses.kernel.system.modular.organization.service.HrOrganizationService;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.file.api.FileOperatorApi;
import cn.stylefeng.roses.kernel.file.api.constants.FileConstants;
import cn.stylefeng.roses.kernel.file.api.expander.FileConfigExpander;
import cn.stylefeng.roses.kernel.file.api.pojo.props.LocalFileProperties;
import cn.stylefeng.roses.kernel.file.api.pojo.request.SysFileInfoRequest;
import cn.stylefeng.roses.kernel.file.api.pojo.response.SysFileInfoResponse;
import cn.stylefeng.roses.kernel.file.modular.entity.SysFileInfo;
import cn.stylefeng.roses.kernel.file.modular.service.SysFileInfoService;
import cn.stylefeng.roses.kernel.rule.enums.YesOrNotEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 作品表;控制器
 *
 * @author songq
 * @date 2025/04/22 14:49
 */
@RestController
@ApiResource(name = "作品表;")
public class WorksController {

    @Resource
    private WorksService worksService;
    @Resource
    private SysFileInfoService sysFileInfoService;
    
    @Resource
    private HrOrganizationService hrOrganizationService;
    
    @Resource
    private FileOperatorApi fileOperatorApi;
    @Resource
    private VoteHistoryService voteHistoryService;

    /**
     * 添加
     *
     * @author songq
     * @date 2025/04/22 14:49
     */
    @PostResource(name = "添加", path = "/works/add")
    public ResponseData<Works> add(@RequestBody @Validated(WorksRequest.add.class) WorksRequest worksRequest) {
        worksService.add(worksRequest);
        return new SuccessResponseData<>();
    }

    /**
     * 删除
     *
     * @author songq
     * @date 2025/04/22 14:49
     */
    @PostResource(name = "删除", path = "/works/delete")
    public ResponseData<?> delete(@RequestBody @Validated(WorksRequest.delete.class) WorksRequest worksRequest) {
        worksService.del(worksRequest);
        return new SuccessResponseData<>();
    }

    /**
     * 编辑
     *
     * @author songq
     * @date 2025/04/22 14:49
     */
    @PostResource(name = "编辑", path = "/works/edit")
    public ResponseData<?> edit(@RequestBody @Validated(WorksRequest.edit.class) WorksRequest worksRequest) {
        worksService.edit(worksRequest);
        return new SuccessResponseData<>();
    }

    /**
     * 查看详情
     *
     * @author songq
     * @date 2025/04/22 14:49
     */
    @GetResource(name = "查看详情", path = "/works/detail")
    public ResponseData<Works> detail(@Validated(WorksRequest.detail.class) WorksRequest worksRequest) {
    	Works works = worksService.detail(worksRequest);
    	HrOrganization ho = hrOrganizationService.getById(works.getWorkDept());
    	works.setWorkDeptName(ho.getOrgName());
//		
		// 拼接文件可直接访问的url
		SysFileInfo img =  sysFileInfoService.getById(works.getWorkImg());
        String fileAuthUrl;
        fileAuthUrl = fileOperatorApi.getFileUnAuthUrl(img.getFileBucket(), img.getFileObjectName());
		
        works.setWorkImgUrl(fileAuthUrl);
		
		SysFileInfo video =  sysFileInfoService.getById(works.getWorkUrl());
        String contextPath = HttpServletUtil.getRequest().getContextPath();
		String fileUrl = FileConfigExpander.getServerDeployHost() + contextPath + "/previewFiles/" + video.getFileBucket() + "/" + video.getFileObjectName();
		works.setWorkVideoUrl(fileUrl);
        return new SuccessResponseData<>(works);
    }

    /**
     * 获取列表
     *
     * @author songq
     * @date 2025/04/22 14:49
     */
    @GetResource(name = "获取列表", path = "/works/list")
    public ResponseData<List<Works>> list(WorksRequest worksRequest) {
    	List<Works>  works = worksService.findList(worksRequest);
    	List<Works>  worksResults = new ArrayList<>();
    	for(Works w : works) {
    		HrOrganization ho = hrOrganizationService.getById(w.getWorkDept());
    		Works work = new Works();
    		BeanUtil.copyProperties(w, work);
    		
    		work.setWorkDeptName(ho.getOrgName());
    		
    		// 拼接文件可直接访问的url
    		SysFileInfo img =  sysFileInfoService.getById(w.getWorkImg());
            String fileAuthUrl;
            fileAuthUrl = fileOperatorApi.getFileUnAuthUrl(img.getFileBucket(), img.getFileObjectName());
    		
    		work.setWorkImgUrl(fileAuthUrl);
    		
    		SysFileInfo video =  sysFileInfoService.getById(w.getWorkUrl());
            String contextPath = HttpServletUtil.getRequest().getContextPath();
    		String fileUrl = FileConfigExpander.getServerDeployHost() + contextPath + "/previewFiles/" + video.getFileBucket() + "/" + video.getFileObjectName();
    		
    		work.setWorkVideoUrl(fileUrl);
            worksResults.add(work);
    		
    	}
        return new SuccessResponseData<>(worksResults);
    }

    /**
     * 获取列表（带分页）
     *
     * @author songq
     * @date 2025/04/22 14:49
     */
    @GetResource(name = "分页查询", path = "/works/page")
    public ResponseData<PageResult<Works>> page(WorksRequest worksRequest) {
    	PageResult<Works>  works = worksService.findPage(worksRequest);
    	List<Works>  worksResults = new ArrayList<>();
    	for(Works w : works.getRows()) {
    		HrOrganization ho = hrOrganizationService.getById(w.getWorkDept());
    		Works work = new Works();
    		BeanUtil.copyProperties(w, work);
    		
    		work.setWorkDeptName(ho.getOrgName());
    		
    		// 拼接文件可直接访问的url
    		SysFileInfo img =  sysFileInfoService.getById(w.getWorkImg());
            String fileAuthUrl;
            fileAuthUrl = fileOperatorApi.getFileUnAuthUrl(img.getFileBucket(), img.getFileObjectName());
    		
    		work.setWorkImgUrl(fileAuthUrl);
    		
    		SysFileInfo video =  sysFileInfoService.getById(w.getWorkUrl());
            String contextPath = HttpServletUtil.getRequest().getContextPath();
    		String fileUrl = FileConfigExpander.getServerDeployHost() + contextPath + "/previewFiles/" + video.getFileBucket() + "/" + video.getFileObjectName();
    		
    		work.setWorkVideoUrl(fileUrl);
    		worksResults.add(work);
    		
    	}
    	works.setRows(worksResults);
        return new SuccessResponseData<>(works);
    }
   
    
    @PostResource(name = "上传视频文件", path = "/works/upload", requiredPermission = false)
    public ResponseData<SysFileInfoResponse> upload(@RequestPart("file") MultipartFile file, @Validated(SysFileInfoRequest.add.class) SysFileInfoRequest sysFileInfoRequest) {
    	SysFileInfoResponse fileUploadInfoResult = this.sysFileInfoService.uploadFile(file, sysFileInfoRequest);
        String contextPath = HttpServletUtil.getRequest().getContextPath();
        String fileUrl = FileConfigExpander.getServerDeployHost() + contextPath + "/previewFiles/" + fileUploadInfoResult.getFileBucket() + "/" + fileUploadInfoResult.getFileObjectName();
 
    	fileUploadInfoResult.setFileUrl(fileUrl);
    	return new SuccessResponseData<>(fileUploadInfoResult);
    }

    @GetResource(name = "获取列表", path = "/works/workConfig")
    public ResponseData<Map<String, Object>> workConfig(WorksRequest worksRequest) {
        HashMap<String, Object> map = new HashMap<>();

        String begin = ConfigContext.me().getSysConfigValueWithDefault("VOTE_BEGIN_TIME", String.class, "");
        String end = ConfigContext.me().getSysConfigValueWithDefault("VOTE_END_TIME", String.class, "");
        String maxNum = ConfigContext.me().getSysConfigValueWithDefault("TOVE_NUM", String.class, "");
        map.put("begin", begin);
        map.put("end", end);
        map.put("maxNum", maxNum);
        return new SuccessResponseData<>(map);
    }

}
